﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;
using Mysqlx;
using Mysqlx.Crud;
using Meiam.System.Core;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///  组件CRM系统OCR识别
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CRMOCRSignController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;
        public readonly string con_oa;
        public readonly string gz_con;


        public CRMOCRSignController(ILogger<CRMOCRSignRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_oa = _configuration.GetConnectionString("OA_DbConnection");
            gz_con = _configuration.GetConnectionString("GZ_WMS_DbConnection");
            _logger = loggerFactory.CreateLogger<CRMOCRSignController>();
        }

        /// <summary>
        /// 组件CRM系统OCR识别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostOCRSign([FromBody] CRMOCRSignRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            CRMOCRSignResponseDto re = new CRMOCRSignResponseDto();
            string ddm_token_crm = "&token=eyJ4ZGFwdGVuYW50aWQiOiIzMzk4MTY5MTc5MDY3NTE0ODkiLCJ4ZGFwdGltZXN0YW1wIjoiMTc1MTMzODExOTAwMCJ9&download=download&formId=685cfa1f9dce705175948c57&uuid=80214dad8c6e29b1716047bb";

            try
            {
                var fj = JsonConvert.DeserializeObject<DDM__adjunct[]>(strparm.order_adjunct);
                if (fj != null)
                {
                    string delivery_no = "";

                    if (fj.Length>1)
                    {
                        strMsg = "当前上传记录，存在附件<"+ fj.Length + ">个，单个表单只能上传一个，请确认后再试！";
                    }
                    else
                    {
                        foreach (var rows in fj)
                        {
                            string url = rows.url + ddm_token_crm;

                            CRMOCR_RequestDto str_url = new CRMOCR_RequestDto();
                            str_url.url = url;

                            Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                            urldic.Add("function_description", "CRM送货单OCR识别");//查看URL配置表地址描述
                            DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                            if (url_dt.Rows.Count > 0)
                            {
                                string jsonText = JsonConvert.SerializeObject(str_url);
                                var reAgv = DB.httpPost_OCR(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "68538461e80cf96ad11fa229", "是");
                                DeliveryOrder psp = JsonConvert.DeserializeObject<DeliveryOrder>(reAgv);
                                if (psp.Code == 200)
                                {
                                    delivery_no =  psp.DeliveryNo.ToString().Trim();

                                    if (delivery_no.Contains("S0"))
                                    {
                                        string original = delivery_no;
                                        StringBuilder sb = new StringBuilder(original);

                                        // 第二位字符的索引是1（因为索引从0开始）
                                        sb[1] = 'O';
                                        delivery_no = sb.ToString();
                                    }

                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("signorder_no", delivery_no);
                                    DataTable check_dt = MethodHelp.GetTableInfo("TMS0202", dic, con);
                                    if (check_dt.Rows.Count<1)
                                    {
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("UDF01", delivery_no);
                                        string strSql2 = MethodHelp.GetTranSQL("TMS0201", dic, con);//获取WMS送货数据SQL
                                        if (strSql2 != "")
                                        {
                                            DataTable ship_dt = DB.OracleQuery(strSql2.ToString(), gz_con);//获取WMS送货单数据
                                            if (ship_dt.Rows.Count > 0)
                                            {
                                                re.data = DB.TableToListModel<CRMOCRSign_DataResponseDto>(ship_dt);
                                            }
                                            else
                                            {
                                                strMsg = "送货单号=<" + delivery_no + ">,获取WMS送货单信息失败！";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        strMsg = "送货单号=<" + delivery_no + ">,已存在上传记录，请确认后再试！";
                                    }                                  
                                }
                                else
                                {
                                    strMsg = "OCR识别失败，请确认图片是否异常！";
                                }
                            }

                        }

                    }                    
                }

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
